/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agol.rent.system.service;


import agol.rent.system.entity.UserApp;
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author AgoL - Daffa
 */
public class LoginServiceImpl implements LoginService {
    
    private Connection connection;
    private PreparedStatement FindUserByUserAndPassword;
    
    private final String QRY_LOGIN = "select * from r_user where" +
            " r_user.username = ? and r_user.password = ?" ;
    
    public LoginServiceImpl(Connection connection){
        try {
            // Ada Tiga Metode penanganan Kesalahan Block Try catch
            
          /*  
           yang ke 1
           this.connection = connection;
           FindUserByUserAndPassword = (PreparedStatement) this.connection.prepareStatement(QRY_LOGIN);
            ========================================================================================= 
          */
            
            // yang ke 2
           /*  this.connection = connection;
            try {
                FindUserByUserAndPassword = (PreparedStatement) this.connection.prepareStatement(QRY_LOGIN);
            } catch (SQLException ex) {
                Logger.getLogger(LoginServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
           */ // =====================================================================================
            
            // yang ke 3
            
            this.connection = (Connection) connection;
            FindUserByUserAndPassword = (PreparedStatement) this.connection.prepareStatement(QRY_LOGIN);
        } catch (SQLException ex) {
            Logger.getLogger(LoginServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        // =============================================================================================
    }
    
    @Override
    public UserApp login(String username, String password) {
       try{
           // Lakukan Pencarian Berdasarkan Username Dan Password
           FindUserByUserAndPassword.setString(1, username);
           FindUserByUserAndPassword.setString(2, password);
           
           
           // Ambil resultset nya
           ResultSet rs = FindUserByUserAndPassword.executeQuery();
           while (rs.next()){
               UserApp userApp = new UserApp();
               userApp.setId(rs.getInt("id"));
               userApp.setUsername(rs.getString("username"));
               userApp.setPassword(rs.getString("password"));
               
               return userApp;
           }
       } catch (SQLException ex){
           Logger.getLogger(LoginServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
       }
         return null;
    }
    
}
